<?php
namespace Admin\Controller;

/**
 * 前台首页控制器
 */
class WithdrawalController extends AdminController {

	
    public function index(){
        /* 查询条件初始化 */
        $map = array();
        $map  = array('del_flag' => 0);
        // if(isset($_GET['name'])){
        //     $map['name']    =   array('like', '%'.(string)I('name').'%');
        // }
        $status = I('status');
        $alipay = I('alipay');
        if($status){
            $map['status'] = $status;
        }
        if($alipay){
            $map['alipay'] = array('alipay', '%'.$alipay);
        }
        $list = $this->lists('withdrawal', $map,'createAt,id');
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->assign('alipay', $alipay);
        $this->meta_title = '用户提现申请';
        $this->display();
    }

    public function apply_approve(){
        // fetch data
        $id = I('id');
        $comment = I('comment');
        $dealName = I('dealName');
        if(!$dealName){
            $this->error('打款者账户不可为空');
            return;
        }
        $m = M('Withdrawal');
        $info = $m->where(array('id' => intval($id)))->find();
        $clientid = $info['clientid'];
        $amount = floatval($info['amount']);
        $mClient = M('Client');
        $balance = $mClient->where(array('id' => intval($clientid)))->getField('balance');
        
        if(!$balance){
            $this->error('用户余额读取失败');
            return;
        }
        if($balance < $amount * 100){
            $this->error('提现金额超出用户余额');
            return;
        }
        $r1 = $m->where(array('id' => intval($id)))->save(array(
            'status' => 'DEAL',
            'dealAt' => $now,
            'updateAt' => $now,
            'dealName' => $dealName,
            'comment' => $comment,
        ));
        if($r1){
            // update client balance
            $r2 = $mClient->where(array('id' => intval($clientid)))->setDec('balance' , intval($amount * 100));
            if($r2){
                $this->success('受理成功');
            }else{
                echo $m->getLastSql();
                $this->error('受理失败2');
            }
        }else{
            $this->error('系统错误1');
        }
    }

    public function apply_handle(){
        $id = I('id');
        // fetch data
        $m = M('Withdrawal');
        $data = $m->where(array('id' => $id))->find();
        if($data){
            $m = M('Client');

            $client = $m->where(array('id' => intval($data['clientid'])))->find();
            $this->assign('client', $client);
        }else{
            $this->error('该信息不存在');
            return;
        }
        $this->assign('data', $data);
        $this->display();
    }


}
?>